<?php
declare (strict_types = 1);

namespace app\command;

use app\api\consDir\CommunityConst;
use app\common\models\Community\CommunityOrder;
use app\common\models\Community\CommunityRank;
use app\common\models\Community\RankMember;
use app\common\models\Member\Member;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class Rank extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('rank')
            ->setDescription('the rank command');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $now = date('Y-m-d H:i:s');
        $where = [
            ['is_switch','=',1],
            ['status','=',1],
            ['deleted','=',0],
            ['start_time','<=',$now],
            ['end_time','>=',$now],
        ];
        $rank = \app\common\models\Community\Rank::getInstance()->where($where)->find();
        if(empty($rank)){
            return false;
        }

        // 获取本周第一天（默认以周一为第一天）
        $firstDayOfWeek = date('Y-m-d H:i:s', strtotime('this week Monday'));

        // 获取本周最后一天（默认以周日为最后一天）
        $lastDayOfWeek = date('Y-m-d 23:59:59', strtotime('this week Sunday'));

        echo "本周开始时间: " . $firstDayOfWeek . "\n";
        echo "本周结束时间: " . $lastDayOfWeek . "\n";
        $where = [
            ['deleted','=',0],
            ['status','=',1],
            ['is_logout','=',0],
        ];
        $userIds = RankMember::getInstance()->where('deleted',0)->column('user_id');
        if(!empty($userIds)){
            $where[] = ['id','not in',$userIds];
        }
        $list = Member::getInstance()->where($where)->select();
        foreach($list as $v){
            try{
                $where = [
                    ['user_id','=',$v['id']],
                    ['status','=',2],
                    ['create_at','between',[$firstDayOfWeek,$lastDayOfWeek]]
                ];
                $perNum = CommunityOrder::getInstance()->where($where)->count();
                $where = [
                    ['m.invite_id','=',$v['id']],
                    ['o.status','=',CommunityConst::ORDER_PAY],
                    ['o.create_at','between',[$firstDayOfWeek,$lastDayOfWeek]]
                ];
                //直推会员参与社区
                $directNum = CommunityOrder::getInstance()
                    ->alias('o')
                    ->leftJoin('member m','o.user_id=m.id')
                    ->where($where)
                    ->count();
                if($perNum <= 0 && $directNum <= 0){
                    continue;
                }
                $where = [
                    ['user_id','=',$v['id']],
                    ['start_time','=',$firstDayOfWeek]
                ];
                $rank = CommunityRank::getInstance()->where($where)->find();
                $data = [
                    'user_id' => $v['id'],
                    'phone' => $v['phone'],
                    'num' => bcadd((string)$perNum, (string)$directNum),
                    'per_num' => $perNum,
                    'direct_num' => $directNum,
                    'start_time' => $firstDayOfWeek,
                    'end_time' => $lastDayOfWeek
                ];
                if($rank){
                    $data['update_at'] = date('Y-m-d H:i:s');
                    CommunityRank::getInstance()->where('id',$rank['id'])->update($data);
                }else{
                    CommunityRank::getInstance()->insert($data);
                }
            }catch (\Exception $e){;
                Log::error('userId:'.$v['id'].$e->getMessage());
            }
        }

        // 指令输出
        $output->writeln('rank');
    }
}
